#include "StdAfx.h"
#include "ActionQueue.h"

CActionQueue::CActionQueue(QObject *parent)
	: QThread(parent)
{

}

CActionQueue::~CActionQueue()
{

}

void CActionQueue::Enqueue( IActionItem *item, bool highPriority /*= false*/ )
{
	m_lock.lock();
	try 
	{
		if (highPriority)
			m_queue.push_front(item);
		else
			m_queue.push_back(item);

		m_queueNotEmpty.wakeAll();
		m_lock.unlock();
	}
	catch (...)
	{
		m_lock.unlock();
		throw;
	}
}

IActionItem* CActionQueue::Dequeue()
{
	m_lock.lock();
	try 
	{
		IActionItem *item = m_queue.takeFirst();
		m_lock.unlock();
		return item;
	}
	catch (...)
	{
		m_lock.unlock();
		throw;
	}
}

void CActionQueue::run()
{
	m_running = true;
	
	while (m_running)
	{
		// Wait for an item to be queued
		m_lock.lock();
		while (m_queue.isEmpty())
			m_queueNotEmpty.wait(&m_lock);

		// Grab it
		IActionItem *item = m_queue.takeFirst();
		m_lock.unlock();

		// Run it
		item->Run();
		item->Complete();
		delete item;
	}
}

void CActionQueue::Shutdown()
{
	m_running = false;
}